package com.par;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;

public class MainActivity extends Activity {
	private static boolean autoUpdate;

	public static final String APP_PREFERENCES = "mysettings";
	public static final String APP_PREFERENCES_AUTO_UPDATE = "AutoUpdate";
	public static final String APP_PREFERENCES_LAUNCHED = "isLaunched";

	private SharedPreferences settings;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		settings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);

		showDialogIfNeeded();

		ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		
		NetworkInfo n =  conMgr.getActiveNetworkInfo();

		if(n != null && n.isConnectedOrConnecting()){
			new UpdateTask().execute("");
		}
	}

	private void showDialogIfNeeded() {
		if (settings.getString(APP_PREFERENCES_LAUNCHED, null) != null) {
			return;
		}

		Editor editor = settings.edit();
		editor.putString(APP_PREFERENCES_LAUNCHED, "true");
		editor.commit();

		final Dialog update = new Dialog(this);
		update.requestWindowFeature(Window.FEATURE_NO_TITLE);
		update.setContentView(R.layout.update_dialog);
		update.setCanceledOnTouchOutside(false);

		Button buttonYes = (Button) update.findViewById(R.id.buttonYes);
		Button buttonNo = (Button) update.findViewById(R.id.buttonNo);

		buttonYes.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				saveSettings(true);
				update.dismiss();
			}

		});

		buttonNo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				saveSettings(false);
				update.dismiss();
			}
		});

		update.show();
	}

	private void saveSettings(boolean value) {
		Editor editor = settings.edit();
		editor.putBoolean(APP_PREFERENCES_AUTO_UPDATE, value);
		editor.commit();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void settingsButton_Click(View v) {
		Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
		intent.putExtra("autoUpdate", autoUpdate);
		startActivity(intent);
	}

	public void searchSaunas(View view) {
		Intent intent = new Intent(MainActivity.this, SearchActivity.class);
		startActivity(intent);
	}

	public void exitButton_Click(View v) {
		finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == 1) {
			autoUpdate = data.getExtras().getBoolean("autoUpdate");
		}
	}

	private class UpdateTask extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			StringBuilder total = new StringBuilder();
			try {
				URL url = new URL("http://par.com.ua/ad345dsfddm");

				HttpURLConnection urlConnection = (HttpURLConnection) url
						.openConnection();

				urlConnection.setRequestMethod("GET");
				urlConnection.setDoOutput(true);
				urlConnection.connect();

				InputStream inputStream = urlConnection.getInputStream();

				BufferedReader r = new BufferedReader(new InputStreamReader(
						inputStream));

				String line = r.readLine();
				total.append(line);

			} catch (Exception e) {
				e.printStackTrace();
			}

			return total.toString();
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			String actualMd5 = settings.getString("saunasUpdateMd5", "");

			if (result != null && !actualMd5.equals(result)) {
				Editor editor = settings.edit();
				editor.putString("saunasUpdateMd5", result);
				editor.commit();

				new UpdateDbTask().execute("");
			} else {
				// Db is up to date
			}
		}
	}

	private class UpdateDbTask extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			StringBuilder total = new StringBuilder();
			try {
				URL url = new URL("http://par.com.ua/ad345dsfdd");

				HttpURLConnection urlConnection = (HttpURLConnection) url
						.openConnection();

				urlConnection.setRequestMethod("GET");
				urlConnection.setDoOutput(true);
				urlConnection.connect();

				InputStream inputStream = urlConnection.getInputStream();

				BufferedReader r = new BufferedReader(new InputStreamReader(
						inputStream));

				String line;
				while ((line = r.readLine()) != null) {
					total.append(line);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}

			return total.toString();
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			if (result != null) {
				Editor editor = settings.edit();
				editor.putString("saunasRaw", result);
				editor.commit();
			}
		}
	}

}
